package com.tianji.learning.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LEARNING_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.WRITE_REPLY;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2024-06-25
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {
    private final UserClient userClient;

    private final IInteractionQuestionService interactionQuestionService;

    private final RabbitMqHelper rabbitMqHelper;

    @Override
    public PageDTO<ReplyVO> pageQuery(ReplyPageQuery replyPageQuery,Boolean isStudent) {
        Long answerId = replyPageQuery.getAnswerId();
        Long questionId = replyPageQuery.getQuestionId();
        //判断参数是否为空
        if (ObjectUtil.isEmpty(questionId) && ObjectUtil.isEmpty(answerId)) {
            return PageDTO.empty(0L, 0L);
        }
        //1805611252666241025
        //分页查询问答评论表
        Page<InteractionReply> page =null;
           if (ObjectUtil.isEmpty(answerId)){
             page=this.lambdaQuery()
                    .eq(ObjectUtil.isEmpty(answerId), InteractionReply::getQuestionId, questionId)
                    .eq(InteractionReply::getAnswerId, 0)
                     .eq(isStudent,InteractionReply::getHidden,false)
                    .page(replyPageQuery.toMpPage());
            }else if (ObjectUtil.isEmpty(questionId)){
               page=this.lambdaQuery()
                       .eq(ObjectUtil.isEmpty(answerId), InteractionReply::getQuestionId, questionId)
                       .eq(ObjectUtil.isEmpty(questionId),InteractionReply::getAnswerId,  answerId)
                       .eq(isStudent,InteractionReply::getHidden,false)
                       .page(replyPageQuery.toMpPage());
           }

        List<InteractionReply> records = page.getRecords();


        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        //获取用户id集合，获取回复目标id
        Set<Long> userIds = new HashSet<>(records.size());
        Set<Long> targetUserIds = new HashSet<>(records.size());
        //Set<Long> answerIds = new HashSet<>(records.size());
        for (InteractionReply record : records) {
                userIds.add(record.getUserId());
                targetUserIds.add(record.getTargetUserId());

            //answerIds.add(record.getAnswerId());
        }
        //根据用户id查询用户信息
        List<UserDTO> userDTOList = userClient.queryUserByIds(userIds);
        Map<Long, UserDTO> userDTOMap = new HashMap<>(userIds.size());
        if (ObjectUtil.isNotEmpty(userDTOList)) {
            userDTOMap = userDTOList.stream().collect(Collectors.toMap(UserDTO::getId, userDTO -> userDTO));
        }
        //封装回复VO
        List<ReplyVO> replyVOS = new ArrayList<>(records.size());
        for (InteractionReply record : records) {
            ReplyVO replyVO = BeanUtil.toBean(record, ReplyVO.class);
            Long userId = record.getUserId();

            UserDTO userDTO = userDTOMap.get(userId);
            if (ObjectUtil.isNotEmpty(userDTO)) {
                if (isStudent && record.getAnonymity().equals(false)){
                    replyVO.setUserName(userDTO.getName());
                    replyVO.setUserIcon(userDTO.getIcon());
                }else if (!isStudent){
                    replyVO.setUserName(userDTO.getName());
                    replyVO.setUserIcon(userDTO.getIcon());
                }

            }
            UserDTO userDTO1 = userDTOMap.get(record.getTargetUserId());
            if (ObjectUtil.isNotEmpty(userDTO1)) {
                replyVO.setTargetUserName(userDTO1.getName());
            }

            replyVOS.add(replyVO);
        }

        return PageDTO.of(page, replyVOS);
    }

    @Override
    public void manageHiddenComments(Long id, boolean hidden) {


        //如果id是评论端则隐藏该评论以及该评论下的所有回复
        InteractionReply reply = lambdaQuery().eq(InteractionReply::getId, id)
                .one();
        if (ObjectUtil.isNotEmpty(reply)) {
            //直接修改
            lambdaUpdate().eq(InteractionReply::getId, id)
                    .set(InteractionReply::getHidden, hidden)
                    .update();
        }else {
            return;
        }

            Long userId = reply.getUserId();
           lambdaUpdate().eq(InteractionReply::getAnswerId,userId)
                   .set(InteractionReply::getHidden,hidden);

            lambdaUpdate().eq(InteractionReply::getAnswerId, id)
                    .set(InteractionReply::getHidden, hidden)
                    .update();
        }


    @Override
    public void addReply(ReplyDTO replyDTO) {

        InteractionReply reply = BeanUtil.toBean(replyDTO, InteractionReply.class);
        reply.setUserId(UserContext.getUser());
        boolean save = save(reply);
        log.error("新增{}",save);

        if ("null".equals(reply.getAnswerId())|| replyDTO.getIsStudent()) {

            interactionQuestionService.lambdaUpdate()
                    .eq(InteractionQuestion::getId, replyDTO.getQuestionId())
                    .set(ObjectUtil.isEmpty(reply.getAnswerId()), InteractionQuestion::getLatestAnswerId, reply.getId())
                    .setSql(ObjectUtil.isEmpty(reply.getAnswerId()),"answer_times = answer_times + 1")
                    .set(InteractionQuestion::getStatus, QuestionStatus.UN_CHECK.getValue())
                    .update();

        }
             lambdaUpdate().eq(InteractionReply::getQuestionId, replyDTO.getQuestionId())
                     .eq(InteractionReply::getId,replyDTO.getAnswerId())
                     .eq(InteractionReply::getUserId,UserContext.getUser())
                     .setSql("reply_times = reply_times + 1")
                     .update();

        try {
            rabbitMqHelper.send(LEARNING_EXCHANGE,WRITE_REPLY,UserContext.getUser());
        } catch (Exception e) {
           log.error("回答新增积分失败");
        }

    }


    }

